package dwz.web.management;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.baidu.ueditor.PathFormat;

import dwz.cms.article.common.HtmlUtil;
import dwz.cms.article.impl.IArticleDisp;
import dwz.cms.article.impl.IArticleOpe;
import dwz.cms.article.impl.IChannelService;
import dwz.persistence.ArticleConditionVO;
import dwz.persistence.BaseConditionVO;
import dwz.persistence.beans.Article;
import dwz.persistence.beans.CmsChannel;
import dwz.persistence.beans.CmsSysUser;
import dwz.persistence.mapper.ArticleMapper;
import dwz.persistence.mapper.CmsArtChannelMapper;

import dwz.persistence.mapper.CmsChannelMapper;
import dwz.persistence.mapper.CmsSysUserMapper;
import dwz.web.BaseController;

@Controller("management.articleController")
@RequestMapping(value = "/management/article")
public class ArticleController extends BaseController {
	static {
		System.out.println("This is ArticleDisp");
	}

	@Autowired
	private IArticleDisp articleDispService;
	@Autowired
	private IChannelService channelService;
	@Autowired
	private IArticleOpe articleDraftOpeService;

	@Resource
	CmsArtChannelMapper cmsArtChannelMapper;

	@Resource
	CmsChannelMapper cmsChannelMaper;
	@Resource
	CmsSysUserMapper cmsSysUserMapper;

	@Resource
	ArticleMapper articleMapper;

	/**
	 * 初始化频道列表
	 * 
	 * @param channelid
	 * @param vo
	 * @param model
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/show/{channelId}")
	public String list(@PathVariable("channelId") int channelid, ArticleConditionVO vo, Model model) {

		Map<String, List> map = articleDispService.searchArticle(vo, channelid);
		List<Article> cmsArticleList = map.get("articleList");
		List<Short> topList = map.get("topList");

		int totalCount = articleDispService.searchArticleNum(vo, channelid);
		model.addAttribute("articleList", cmsArticleList);
		model.addAttribute("topList", topList);
		vo.setTotalCount(totalCount);
		model.addAttribute("vo", vo);
		model.addAttribute("pageSize", vo.getPageSize());

		return "/ArticleManagement/article/articleList";
	}

	/**
	 * 写稿界面初始化
	 * 
	 * @param channelid
	 * @param vo
	 * @param model
	 * @return
	 */
	@RequestMapping("/add/{channelId}")
	public String addShow(@PathVariable("channelId") int channelid, BaseConditionVO vo, Model model) {

		List<CmsSysUser> sysUserList = cmsSysUserMapper.selectSysUserList();
		String channelName = cmsChannelMaper.selectChannelNameByChannelId(channelid);

		StringBuffer sbAuthor = new StringBuffer();
		for (CmsSysUser sysUser : sysUserList) {
			sbAuthor.append("<option value=\"" + sysUser.getId() + "\">" + sysUser.getName() + "</option>");
		}

		System.out.println(sbAuthor);

		StringBuffer sbKeyword = new StringBuffer();
		sbKeyword.append("<option value=\"\">无</option>" + "<option value=\"http://www.jseea.cn/highschool.html\">普通高校招生</option>"
				+ "<option value=\"http://www.jseea.cn/graduateenrollment.html\">研究生招生</option>"
				+ "<option value=\"http://www.jseea.cn/adulthighschool.html\">成人高校招生</option>"
				+ "<option value=\"http://www.jseea.cn/selflearning.html\">自学考试</option>"
				+ "<option value=\"http://www.jseea.cn/seniorhighschoollevel.html\">高中学业水平测试</option>"
				+ "<option value=\"http://www.jseea.cn/certificateexamination.html\">证书考试</option>");

		System.out.println(sbKeyword);

		model.addAttribute("authors", sbAuthor.toString());
		model.addAttribute("keyword", sbKeyword.toString());
		Date date = new Date();
		String tempString = HtmlUtil.generateCode(date);
		model.addAttribute("currentCode", tempString);
		model.addAttribute("currentChannelId", channelid);
		model.addAttribute("currentChannelName", channelName);
		model.addAttribute("naveTabId", "channel_" + channelid);
		model.addAttribute("vo", vo);
		return "/ArticleManagement/article/addArticle";
	}

	/**
	 * 写稿 保存
	 * 
	 * @param article
	 * @return
	 */
	@RequestMapping(value = "/addSave/{channelId}", method = RequestMethod.POST)
	public ModelAndView addSave(@PathVariable("channelId") int channelid, Article article) {
		
		if (article.getChannelids()==""||article.getChannelids()==null||"test.ids".equals(article.getChannelids())) {
			article.setChannelids(channelid+"");
		}

		articleDraftOpeService.saveArticle(article, "");

		return ajaxDoneSuccess(getMessage("msg.operation.success"));

	}

	/**
	 * 查看稿件
	 * 
	 * @param articleId
	 * @param vo
	 * @param model
	 * @return
	 */
	@RequestMapping("/view/{slt_articleId}")
	public String view(@PathVariable("slt_articleId") String articleId, BaseConditionVO vo, Model model) {
		Article article = articleDispService.getArticle(articleId);

		List<String> channelList = cmsArtChannelMapper.selectChannelListByCode(articleId);
		List<String> channelListCN = cmsChannelMaper.selectChannelNamebyChannelids(channelList);

		// 对日期进行格式化处理
		// article.setOrgtime(new
		// SimpleDateFormat("yyyyMMddHHmmss").format(article.getOrgtime()););

		model.addAttribute("article", article);
		model.addAttribute("channelIds", listToString(channelListCN, '|'));
		model.addAttribute("firstTop", "否");
		model.addAttribute("vo", vo);
		return "/ArticleManagement/article/viewArticle";
	}

	/**
	 * 改稿界面初始化
	 * 
	 * @param channelid
	 * @param articleId
	 * @param vo
	 * @param model
	 * @return
	 */
	@RequestMapping("/edit/{channelId}/{slt_articleId}")
	public String editShow(@PathVariable("channelId") String channelid, @PathVariable("slt_articleId") String articleId,
			BaseConditionVO vo, Model model) {
		Article article = articleDispService.getArticle(articleId);

		List<CmsSysUser> sysUserList = cmsSysUserMapper.selectSysUserList();

		StringBuffer sb = new StringBuffer();
		for (CmsSysUser sysUser : sysUserList) {
			sb.append("<option value=\"" + sysUser.getId() + "\">" + sysUser.getName() + "</option>");
		}

		System.out.println(sb);
		List<String> channelList = cmsArtChannelMapper.selectChannelListByCode(articleId);
		List<String> channelListCN = cmsChannelMaper.selectChannelNamebyChannelids(channelList);

		model.addAttribute("authors", sb.toString());
		model.addAttribute("article", article);
		model.addAttribute("naveTabId", "channel_" + channelid);
		model.addAttribute("channelIds", listToString(channelList, ','));
		model.addAttribute("channelIdsCN", listToString(channelListCN, ','));
		model.addAttribute("vo", vo);

		return "/ArticleManagement/article/modArticle";
	}

	/**
	 * 改稿 保存
	 * 
	 * @param article
	 * @return
	 */
	@RequestMapping(value = "/editSave", method = RequestMethod.POST)
	public ModelAndView editSave(Article article) {
		Short sState = article.getState();
		// 状态是 已发布 的稿件,需要将其状态重置为 待发布
		if (sState == 4) {
			article.setState((short) 3);
		}

		articleDraftOpeService.updateArticle(article, "");

		return ajaxDoneSuccess(getMessage("msg.operation.success"));

	}

	/**
	 * 删除文章
	 * 
	 * @param articleId
	 * @return
	 */
	@RequestMapping("/delete/{slt_articleId}")
	public ModelAndView deleteArtilce(@PathVariable("slt_articleId") String articleId) {

		Article article = articleMapper.selectArticleByCode(articleId);
		List<String> channelList = cmsArtChannelMapper.selectChannelListByCode(articleId);

		if (article != null && channelList.size() > 0) {
			articleDraftOpeService.delArticle(article, listToString(channelList, ','));
		}

		return ajaxDoneSuccess(getMessage("msg.operation.success"));

	}

	/**
	 * 所属频道选择树 初始化
	 * 
	 * @param channelIds
	 * @param vo
	 * @param model
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/channelIdsSelect/{channelIds}")
	public String channelIdselect(@PathVariable("channelIds") List<String> channelIds, BaseConditionVO vo,
			Model model) {
		// 查询目录列表
		List<CmsChannel> channelList = channelService.selectChannelisNotFirst();

		JSONArray jsonArray = new JSONArray();
		JSONArray jsonArrayMenuGroup = new JSONArray();

		for (CmsChannel channel : channelList) {
			System.out.println(channel.getId() + " " + channel.getFatherid() + " " + channel.getTitle());
			JSONObject jObject = new JSONObject();
			jObject.put("id", channel.getId());
			jObject.put("pId", channel.getFatherid() == 1 ? 0 : channel.getFatherid());
			jObject.put("name", channel.getTitle());

			if ("0".equals(jObject.get("pId").toString())) {
				jsonArrayMenuGroup.put(jObject);
			} else {
				jsonArray.put(jObject);
			}
		}

		StringBuffer sb = new StringBuffer();
		Iterator itMenuGroup = (Iterator) jsonArrayMenuGroup.iterator();
		sb.append("<ul class=\"tree treeFolder treeCheck \" >");
		String strCheck = "";
		while (itMenuGroup.hasNext()) {
			JSONObject menuGroup = (JSONObject) itMenuGroup.next();
			if (channelIds.contains(menuGroup.get("id").toString())) {
				strCheck = "checked=\"true\"";
			} else {
				strCheck = "";
			}
			sb.append("<li><a href=\"javascript:\"  target=\"navTab\" rel=\"channel_" + menuGroup.get("id")
					+ "\" tvalue=" + menuGroup.get("id") + " tname=" + menuGroup.get("name") + " " + strCheck + ">"
					+ menuGroup.get("name") + "</a>");
			Iterator itMenus = (Iterator) jsonArray.iterator();
			StringBuffer sbSecondMenu = new StringBuffer();
			while (itMenus.hasNext()) {

				JSONObject menu = (JSONObject) itMenus.next();
				if (channelIds.contains(menu.get("id").toString())) {
					strCheck = "checked=\"true\"";
				} else {
					strCheck = "";
				}
				// 如果当前menu选项的pId与当前menuGroup的id号相等，则其为menuGroup的子菜单
				if (menu.get("pId").equals(menuGroup.get("id"))) {
					sbSecondMenu.append("<li><a href=\"javascript:\" target=\"navTab\" rel=\"channel_" + menu.get("id")
							+ "\" tvalue=" + menu.get("id") + " tname=" + menu.get("name") + " " + strCheck + ">"
							+ menu.get("name") + "</a></li>");
				}
			}

			if (!"".equals(sbSecondMenu)) {
				sb.append("<ul>");// 二级菜单组开始
				sb.append(sbSecondMenu);
				sb.append("</ul>");// 二级菜单组结束
			}

			sb.append("</li>");// 一级菜单结束
		}

		sb.append("</ul>");// 菜单结束
		System.out.println(sb);

		model.addAttribute("channelTree", sb.toString());
		model.addAttribute("vo", vo);
		return "/ArticleManagement/article/channelTree";
	}

	/**
	 * 频道置顶
	 * 
	 * @param channelId
	 * @param articleId
	 * @param vo
	 * @param model
	 * @return
	 */
	@RequestMapping("/firsttop/{channelId}/{slt_articleId}")
	public ModelAndView firstTop(@PathVariable("channelId") String channelId,
			@PathVariable("slt_articleId") String articleId, BaseConditionVO vo, Model model) {

		articleDraftOpeService.saveTopisNotFirst(articleId, channelId);

		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}

	/**
	 * 频道置顶
	 * 
	 * @param channelId
	 * @param articleId
	 * @param vo
	 * @param model
	 * @return
	 */
	@RequestMapping("/unfirsttop/{channelId}/{slt_articleId}")
	public ModelAndView unFirstTop(@PathVariable("channelId") String channelId,
			@PathVariable("slt_articleId") String articleId, BaseConditionVO vo, Model model) {

		articleDraftOpeService.unsaveTopisNotFirst(articleId, channelId);

		return ajaxDoneSuccess(getMessage("msg.operation.success"));
	}

	/**
	 * List转String(工具函数)
	 * 
	 * @param List
	 * @param separator
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private String listToString(List list, char separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
			if (i < list.size() - 1) {
				sb.append(separator);
			}
		}
		return sb.toString();
	}

	/**
	 * List转String(工具函数)
	 * 
	 * @param List
	 * @param separator
	 * @return
	 */
	@SuppressWarnings("unused")
	private List<String> StringtoToList(String str, String separator) {
		String[] strList = str.split(separator);

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < strList.length; i++) {
			list.add(strList[i]);
		}
		return list;
	}
}
